package com.jt.assistant.ui

import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItems
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.jt.assistant.R
import com.jt.assistant.adapter.CarReceiveAdapter
import com.jt.assistant.adapter.DialogListAdapter
import com.jt.assistant.base.GlobalConfig.ATYPE
import com.jt.assistant.base.GlobalConfig.CARTYPE
import com.jt.assistant.base.GlobalConfig.DESCITYNAME
import com.jt.assistant.base.GlobalConfig.DISPATCH_CAR_ID
import com.jt.assistant.base.GlobalConfig.LICENCE
import com.jt.assistant.base.GlobalConfig.LICENSE_NAME
import com.jt.assistant.base.GlobalConfig.RELATION_ID
import com.jt.assistant.bean.CarReceiveBean
import com.jt.assistant.bean.CarReceiveDetailBean
import com.jt.assistant.bean.Param
import com.jt.assistant.viewmodel.HomeViewModel
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_car_receive.*

/**
 * 车辆交接单
 */
class CarReceiveActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        CarReceiveAdapter(
            ArrayList<CarReceiveBean>()
        )
    }
    private var mLicence = ""
    private var mDay = "1"

    override fun layoutId(): Int = R.layout.activity_car_receive

    override fun initView(savedInstanceState: Bundle?) {
        with(rv_carReceiver) {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter

        }
    }

    override fun initData() {}

    override fun initListener() {

        tv_car_time.setOnClickListener {
            showTimeListDialog()
        }

        set_carReceive.setOnScanListener {
            if (it.isEmpty()) {
                ToastUtils.showShort("请输入车牌号")
                return@setOnScanListener
            }
            val params = Param::class.java.newInstance()
            params.license = it
            params.day = mDay
            viewModel.getIntransitTruck(params)
        }

        viewModel.mGetIntransitTruck.observe(this, {
            log(it)
            if (it.isSuccess()) {
                if (it.data.isEmpty()) ToastUtils.showShort("未搜索到数据")
                mAdapter.data.clear()
                mAdapter.data.addAll(it.data)
                mAdapter.notifyDataSetChanged()
            }
        })

        viewModel.mGetIntransitTruckDetail.observe(this, {
            log(it)
            if (it.isSuccess()) {
                showCarDetail(mLicence, it.data)
            }
        })

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            mLicence = mAdapter.data[position].licence
            val params = Param::class.java.newInstance()
            params.id = mAdapter.data[position].dispatchCarId.toString() + ""
            params.type = mAdapter.data[position].type.toString() + ""
            viewModel.getIntransitTruckDetail(params)
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->

            if (mAdapter.data[position].waybillList.isEmpty()) {
                startActivity(Intent(
                    this@CarReceiveActivity,
                    CarReceiveUploadActivity::class.java
                ).apply {
                    putExtra(DISPATCH_CAR_ID, mAdapter.data[position].dispatchCarId.toString())
                    putExtra(LICENCE, mAdapter.data[position].licence)
                    putExtra(DESCITYNAME, mAdapter.data[position].desCityName)
                    putExtra(CARTYPE, mAdapter.data[position].type.toString())
                })

            } else {
                startActivity(
                    Intent(
                        this@CarReceiveActivity,
                        OrderSelectionActivity::class.java
                    ).apply {
                        putExtra(
                            "waybillList",
                            GsonUtils.toJson(mAdapter.data[position].waybillList)
                        )
                        putExtra(RELATION_ID, mAdapter.data[position].dispatchCarId.toString())
                        //派车类型 1：提货   2：出货(这里再提货交接单 生成电子交接单时需要用到 用来区分交接单类型 直发和提货回仓)'
                        if ( mAdapter.data[position].dispatchType == 1){
                            putExtra(ATYPE, "1")
                        }else if ( mAdapter.data[position].dispatchType == 2){
                            putExtra(ATYPE, "3")
                        }
                        putExtra(LICENSE_NAME, mAdapter.data[position].licence)
                    })
            }

            set_carReceive.clearData()
            mAdapter.data.clear()
            mAdapter.notifyDataSetChanged()
        }
    }

    private fun showCarDetail(
        code: String,
        data: MutableList<CarReceiveDetailBean>
    ) {
        val dialog = MaterialDialog(this).show {
            title(text = "$code 详情")
            positiveButton(text = "确定")
            customView(R.layout.layout_dialog_list, scrollable = false, horizontalPadding = false)
            lifecycleOwner(this@CarReceiveActivity)
        }
        // Setup custom view content
        val customView = dialog.getCustomView()
        val rvDialog: RecyclerView = customView.findViewById(R.id.rv_dialog)
        val listAdapter = DialogListAdapter(ArrayList<String>())
        with(rvDialog) {
            layoutManager = LinearLayoutManager(context)
            adapter = listAdapter
            listAdapter.data.addAll(getContent(data))
            listAdapter.notifyDataSetChanged()
        }
    }


    private fun getContent(data: MutableList<CarReceiveDetailBean>): ArrayList<String> {
        val mData = ArrayList<String>()
        data.forEach {
            val txt = "渠道单号:${it.channelOrderNo}" + "\n" +
                    "目的仓城市:${it.cityName}" + "\n" +
                    "客户名称:${it.customerName}" + "\n" +
                    "箱数:${it.cartonNum}" + "  ${it.volume}m³" + "   ${it.weight}Kg"
            mData.add(txt)
        }
        return mData
    }

    private fun showTimeListDialog() {
        val list = listOf(
            "近一天",
            "近三天",
            "近七天",
        )

        MaterialDialog(this).show {
            listItems(items = list) { _, index, text ->
                this@CarReceiveActivity.tv_car_time.text = text
                mDay = when (index) {
                    0 -> {
                        "1"
                    }
                    1 -> {
                        "3"
                    }
                    else -> {
                        "7"
                    }
                }

                if (this@CarReceiveActivity.set_carReceive.string.isNotEmpty()){
                    val params = Param::class.java.newInstance()
                    params.license = this@CarReceiveActivity.set_carReceive.string
                    params.day = mDay
                    viewModel.getIntransitTruck(params)
                }
            }
            lifecycleOwner(this@CarReceiveActivity)
        }
    }

}